package com.bolt.support.sqlconfig.base;

import com.bolt.support.sqlconfig.builder.SqlSourceBuilder;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;


public class SqlStatement implements SqlSource {
    private String id;
    private String sqlType;
    private Class<?> entity;
    private String parameterType;
    private boolean queryLimit;
    private String tableKey;

    // 查询结果处理器
    private List resultProcessor = new ArrayList();

    public boolean isQueryLimit() {
        return queryLimit;
    }

    public void setQueryLimit(boolean queryLimit) {
        this.queryLimit = queryLimit;
    }

    public String getTableKey() {
        return tableKey;
    }

    public void setTableKey(String tableKey) {
        this.tableKey = tableKey;
    }

    public String getParameterType() {
        return parameterType;
    }

    public void setParameterType(String parameterType) {
        this.parameterType = parameterType;
    }

    private SqlNode rootAqlNode;

    public SqlNode getRootAqlNode() {
        return rootAqlNode;
    }

    public void setRootAqlNode(SqlNode rootAqlNode) {
        this.rootAqlNode = rootAqlNode;
    }

    public String getSqlType() {
        return sqlType;
    }

    public void setSqlType(String sqlType) {
        this.sqlType = sqlType;
    }

    public Class<?> getEntity() {
        return entity;
    }

    public void setEntity(Class<?> entity) {
        this.entity = entity;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public SqlText getSqlText(Object parameterObject) {
        DynamicContext context = new DynamicContext(parameterObject);
        rootAqlNode.apply(context);
        SqlText sqlText;
        if (parameterObject != null) {
            SqlSourceBuilder builder = new SqlSourceBuilder();
            sqlText = builder.parse(context.getSql(), parameterType, context.getBindings());
        } else {
            sqlText = new SqlText(context.getSql(), null);
        }
        sqlText.setEntity(entity);
        return sqlText;
    }

    @Override
    public SqlText getSqlText(Object parameterObject, Sort sort) {
        SqlText sqlText = getSqlText(parameterObject);
        StringBuffer sqlBuffer = new StringBuffer(sqlText.getSql());
        sqlBuffer.append("order by ");
        sqlBuffer.append(sort.toString());
        return sqlText;
    }

    public List getResultProcessor() {
        return resultProcessor;
    }
}
